unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtCtrls;

type
  TForm1 = class(TForm)
    Image1: TImage;
    Timer1: TTimer;
    BitBtn1: TBitBtn;
    procedure FormCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
  private
    procedure draw;
    procedure predraw;
    procedure Lines(x1, y1, b: integer);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
const
  N=5;
  R=20;
  T=50;
  L=50;
  P=20;

var
  i, j, k, o, m: integer;
  arr, lock, pre: array of integer;
  flag: boolean;
procedure TForm1.draw;
begin
  for k:=0 to N-i-1 do
  begin
    image1.Canvas.Brush.Color:=1000*arr[k];
    image1.Canvas.Ellipse(L+P*i+2*R*i, T+P*k+2*R*k, L+P*i+2*R*(i+1), T+P*k+2*R*(k+1));
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  flag:=false;
  randomize;
  setlength(arr, N);
  setlength(lock, N);
  setlength(pre, N);
  for j:=0 to N-1 do
    arr[j]:=random(1000);
  for i:=0 to N-1 do
    lock[i]:=0;
  j:=0;
  k:=0;
  i:=0;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if (arr[j]>arr[j+1]) then
  begin
    o:=arr[j];
    arr[j]:=arr[j+1];
    arr[j+1]:=o;
  end;
  j:=j+1;
  if (j=N-1) then
  begin
    if (i<>0) then
    begin
      for o:=0 to n-i-1 do
        lines(L+P*(i-1)+2*R*(i-1)+R, T+P*o+2*R*o+R, o);
    end;
    draw;
    if (i<>0) then
      predraw;
    j:=0;
    i:=i+1;
    if (i=N) then
    begin
      timer1.Enabled:=false;
    end;
    for o:=0 to N-1 do
      pre[o]:=arr[o];
    for o:=0 to N-1 do
      lock[o]:=0;
  end;
  
end;

procedure TForm1.Lines;
begin
  image1.Canvas.Pen.Color:=clblack;
  image1.Canvas.MoveTo(x1, y1);
  m:=0;
  flag:=false;
  while (lock[m]=1) do
    m:=m+1;
  while (arr[m]<>pre[b]) do
  begin
    flag:=true;
    m:=m+1;
    if (arr[m]=pre[b]) and (lock[m]=0) then
    begin
      image1.Canvas.Pen.Color:=clBlack;
      image1.Canvas.LineTo(L+P*i+2*R*i+R, T+P*m+2*R*m+R);
      lock[m]:=1;
    end;
  end;
  if (flag=false) then
  begin
    image1.Canvas.Pen.Color:=clBlack;
    image1.Canvas.LineTo(L+P*i+2*R*i+R, T+P*m+2*R*m+R);
    lock[m]:=1;
  end;
end;

procedure TForm1.BitBtn1Click(Sender: TObject);
begin
  flag:=false;
  randomize;
  for j:=0 to N-1 do
    arr[j]:=random(1000);
  for i:=0 to N-1 do
    lock[i]:=0;
  j:=0;
  k:=0;
  i:=0;
  image1.Canvas.Brush.Color:=clWhite;
  image1.Canvas.rectangle(clientrect);
  timer1.Enabled:=true;
end;

procedure TForm1.predraw;
begin
  for k:=0 to N-i-1 do
  begin
    image1.Canvas.Brush.Color:=1000*pre[k];
    image1.Canvas.Ellipse(L+P*(i-1)+2*R*(i-1), T+P*k+2*R*k, L+P*(i-1)+2*R*i, T+P*k+2*R*(k+1));
  end;
end;

end.

